package org.jeecg.modules.mstr.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SerializeUtils;
import org.jeecg.modules.mstr.service.IMstrApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MstrApiServiceImpl implements IMstrApiService {

    @Value(value = "${mstr.baseUrl}")
    private String baseUrl;

    @Value(value = "${mstr.username}")
    private String username;

    @Value(value = "${mstr.password}")
    private String password;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SerializeUtils serializeUtils;

    private Cookie globeCookie;

	/***
	 * mstr登录接口
	 * @param username
	 * @param password
	 * @return
	 */
	@Override
	public String login(String username, String password) throws Exception{
		String baseRestURL = baseUrl + "/auth/login";
		HttpClient httpClient = null;
		CookieStore httpCookieStore = new BasicCookieStore();
		HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
		httpClient = builder.build();
		HttpPost httpRequest = new HttpPost(baseRestURL);
		httpRequest.setHeader("Content-Type", "application/json");
		String token = "";
		Map<String, Object> jbody = new HashMap<String, Object>();
		jbody.put("username", username);
		jbody.put("password", password);
		StringEntity body = new StringEntity(JSONObject.toJSON(jbody).toString());
		httpRequest.setEntity(body);

		HttpResponse response = httpClient.execute(httpRequest);
		Header[] headers = response.getAllHeaders();
		for (int i = 0; i < headers.length; i++) {
			Header header = headers[i];
			if (header.getName().equalsIgnoreCase("X-MSTR-AuthToken")) {
				token = header.getValue();
				break;
			}
		}
		//获取cookie
        Cookie cookie = httpCookieStore.getCookies().get(0);
        //保存cookie值到redis
        redisUtil.set(CommonConstant.PREFIX_MSTR_USER_COOKIE + token, cookie);

        this.globeCookie = cookie;

		return token;
	}

	/**
	 * 获取report对象
	 * @param token
	 * @param projectId
	 * @param reportId
	 * @return
	 * @throws Exception
	 */
	@Override
	public JSONObject report(String token, String projectId, String reportId) throws Exception {
        //接口调用url
        String baseRestURL = baseUrl + "/reports/" + reportId;
	    //检验token是否有效
        Integer statusCode = this.session(token);
        if(statusCode != 200){
            //重新登录获取token
            token = this.login(username, password);
        }
		HttpClient httpClient = null;
        CookieStore httpCookieStore = new BasicCookieStore();
        httpCookieStore.addCookie(this.globeCookie);
		HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
		httpClient = builder.build();
		HttpGet httpRequest = new HttpGet(baseRestURL);
        httpRequest.setHeader("Content-Type", "application/json");
		httpRequest.setHeader("X-MSTR-AuthToken", token);
		httpRequest.setHeader("X-MSTR-ProjectID", projectId);
		HttpResponse response = httpClient.execute(httpRequest);
		String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
		statusCode =  response.getStatusLine().getStatusCode();
        JSONObject resultObj = new JSONObject();
        resultObj.put("result", JSONObject.parseObject(resultStr));
        resultObj.put("statusCode", statusCode);
		return resultObj;
	}

    /**
     * 校验token是否有效
     * @param token
     * @return 200
     * @throws Exception
     */
    @Override
    public Integer session(String token) throws Exception {
        String baseRestURL = baseUrl + "/sessions";
        HttpClient httpClient = null;
        CookieStore httpCookieStore = new BasicCookieStore();
        httpCookieStore.addCookie(this.globeCookie);
        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
        httpClient = builder.build();
        HttpGet httpRequest = new HttpGet(baseRestURL);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("X-MSTR-AuthToken", token);
        HttpResponse response = httpClient.execute(httpRequest);
        Integer statusCode = response.getStatusLine().getStatusCode();
        return statusCode;
    }

    /**
     * mstr接口退出
     * @param token
     * @return 204 Success (Session closed)
     * @throws Exception
     */
    @Override
    public Integer logout(String token) throws Exception {
        HttpClient httpClient = null;
        CookieStore httpCookieStore = new BasicCookieStore();
        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
        httpClient = builder.build();
        String baseRestURL = baseUrl + "/sessions";
        HttpPost httpRequest = new HttpPost(baseRestURL);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("Accept", "application/json");
        httpRequest.setHeader("X-MSTR-AuthToken", token);
        HttpResponse response = httpClient.execute(httpRequest);
        Integer statusCode = response.getStatusLine().getStatusCode();
        return statusCode;
    }

    /**
     * 获取车型信息列表
     * @param token
     * @param projectId
     * @param reportId
     * @param attributeId
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject getVehicleTypeList(String token, String projectId, String reportId, String attributeId) throws Exception {
        //接口调用url
        String baseRestURL = baseUrl + "/reports/" + reportId + "/attributes/" + attributeId + "/elements";
        //检验token是否有效
        Integer statusCode = this.session(token);
        if(statusCode != 200){
            //重新登录获取token
            token = this.login(username, password);
        }
        HttpClient httpClient = null;
        CookieStore httpCookieStore = new BasicCookieStore();
        httpCookieStore.addCookie(this.globeCookie);
        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
        httpClient = builder.build();
        HttpGet httpRequest = new HttpGet(baseRestURL);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("X-MSTR-AuthToken", token);
        httpRequest.setHeader("X-MSTR-ProjectID", projectId);
        HttpResponse response = httpClient.execute(httpRequest);
        String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
        statusCode =  response.getStatusLine().getStatusCode();
        JSONArray resultArray = JSONArray.parseArray(resultStr);
        JSONObject resultObj = new JSONObject();
        resultObj.put("statusCode", statusCode);
        resultObj.put("result",resultArray);
        return resultObj;
    }
}
